<?php
abstract class AdminController extends BRail_Application_Controller_Abstract
{
    /**
     * @var string
     */
    private $adminType;

    /**
     * @throws Exception
     */
    public function init()
    {
        $session = new Zend_Session_Namespace('session');
        if (null == $session->authenticatedUser) {
            throw new Exception("Vous n'avez pas accès à cette partie de l'application, veuillez vous authentifier");
        }
    }

    /**
     * @param string $adminType
     */
    public function setAdminType($adminType)
    {
        if (!in_array($adminType, array('store', 'discount'))) {
            throw new Exception('Admin type must be store or discount');
        }

        $this->adminType = $adminType;
    }

    /**
     * @return string
     */
    public function getAdminType()
    {
        return $this->adminType;
    }


    public function indexAction()
    {
        $carouselItemTable = new CarouselItemTable();

        if ($this->getAdminType() == 'store') {
            $carouselItems = $carouselItemTable->getAllStorePictures();
        } else {
            $carouselItems = $carouselItemTable->getAllDiscounts();
        }

        $this->view->carouselItems = $carouselItems;
    }

    public function addAction()
    {
        if ($this->getRequest()->getParam('submit') !== null) {
            //Control inputs
            $errors = array();
            if (null == $this->_getParam('inputText')) {
                $errors[] = 'Le champ "Texte" ne peut être vide';
            }

            if (null == $this->_getParam('inputDateIn')) {
                $errors[] = 'Le champ "Date de début" ne peut être vide';
            }

            if (null == $this->_getParam('inputDateOut')) {
                $errors[] = 'Le champ "Date de fin" ne peut être vide';
            }

            if (!$_FILES['inputFile']['tmp_name']) {
                $errors[] = 'Vous devez choisir un fichier';
            }

            $this->view->errors = $errors;

            if (!$errors) {
                //Save the picture in database
                $table = new CarouselItemTable();
                $carouselItem = $table->createRow();

                $carouselItem
                    ->setDateIn(date_format(date_create_from_format('d/m/Y', $this->_getParam('inputDateIn')), 'Y-m-d'))
                    ->setDateOut(date_format(date_create_from_format('d/m/Y', $this->_getParam('inputDateOut')), 'Y-m-d'))
                    ->setText($this->_getParam('inputText'))
                    ->setType($this->getAdminType())
                    ->save();

                //File treatment
                $fileResizer = new Application_Service_UploadImage();

                $imageType = $carouselItem->isDiscount() ? 'discount' : 'store';
                $fileResizer->uploadAndResizeImages(
                    $_FILES['inputFile']['tmp_name'],
                    $carouselItem->id,
                    $imageType
                );
            }

            $this->_redirect('/admin-' . $this->getAdminType());
        }

        // Reuse edit view
        $this->render('edit');
        $this->view->carouselItem = array();
    }

    public function deleteAction()
    {
        if (($id = $this->getRequest()->getParam('id')) == null) {
            throw new Exception('An id parameter must be given');
        }

        if ((int) $id == 0) {
            throw new Exception('A valid id parameter must be given');
        }

        $carouselItemTable = new CarouselItemTable();
        $carouselItem = $carouselItemTable->find($id)->current();

        if (count($carouselItem) == 0) {
            throw new Exception('The given id does not exist');
        }

        if ($this->getAdminType() == 'store' && !$carouselItem->isStorePicture()) {
            throw new Exception('The given id is not a store picture');
        }

        if ($this->getAdminType() == 'discount' && !$carouselItem->isDiscount()) {
            throw new Exception('The given id is not a discount picture');
        }

        //Delete the files
        $imagesPath = Application::getCarouselPicturesPath() . '/' . $this->getAdminType() . '/';
        $picture = realpath($imagesPath . $carouselItem->id . '.jpg');
        $thumbnail = realpath($imagesPath . 'thumbs/' . $carouselItem->id . '.jpg');

        unlink($picture);
        unlink($thumbnail);

        //Delete record in db
        $carouselItem->delete();

        $this->_redirect('/admin-' . $this->getAdminType());
    }

    public function editAction()
    {
        if (($id = $this->getRequest()->getParam('id')) == null) {
            throw new Exception('An id parameter must be given');
        }

        if ((int) $id == 0) {
            throw new Exception('A valid id parameter must be given');
        }

        $carouselItemTable = new CarouselItemTable();
        $carouselItem = $carouselItemTable->find($id)->current();

        if (count($carouselItem) == 0) {
            throw new Exception('The given id does not exist');
        }

        if ($this->getAdminType() == 'store' && !$carouselItem->isStorePicture()) {
            throw new Exception('The given id is not a store picture');
        }

        if ($this->getAdminType() == 'discount' && !$carouselItem->isDiscount()) {
            throw new Exception('The given id is not a discount picture');
        }

        if ($this->getRequest()->getParam('submit') !== null) {
            //Control inputs
            $errors = array();
            if (null == $this->_getParam('inputText')) {
                $errors[] = 'Le champ "Texte" ne peut être vide';
            }

            if (null == $this->_getParam('inputDateIn')) {
                $errors[] = 'Le champ "Date de début" ne peut être vide';
            }

            if (null == $this->_getParam('inputDateOut')) {
                $errors[] = 'Le champ "Date de fin" ne peut être vide';
            }

            $this->view->errors = $errors;

            if (!$errors) {
                $carouselItem
                    ->setDateIn(date_format(date_create_from_format('d/m/Y', $this->_getParam('inputDateIn')), 'Y-m-d'))
                    ->setDateOut(date_format(date_create_from_format('d/m/Y', $this->_getParam('inputDateOut')), 'Y-m-d'))
                    ->setText($this->_getParam('inputText'))
                    ->save();

                //File treatment
                if ($_FILES['inputFile']['tmp_name']) {
                    $fileResizer = new Application_Service_UploadImage();

                    $imageType = $carouselItem->isDiscount() ? 'discount' : 'store';
                    $fileResizer->uploadAndResizeImages(
                        $_FILES['inputFile']['tmp_name'],
                        $carouselItem->id,
                        $imageType
                    );
                }

                $this->_redirect('/admin-' . $this->getAdminType());
            }
        }

        $this->view->carouselItem = $carouselItem->toArray();
    }
}